package com.net.xpay.admin.secutiry;

import com.net.common.model.ResultData;
import com.net.xpay.common.domain.admin.rbac.AdminUser;
import com.net.xpay.common.domain.admin.rbac.Permission;
import com.net.xpay.common.manager.admin.rbac.AdminUserManager;
import com.net.xpay.common.service.admin.rbac.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
  on 01/02/2018.
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private SecurityHelper securityHelper;

    @Autowired
    private AdminUserManager adminUserManager;

    @Autowired
    private PermissionService permissionService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Long adminUserId = (Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        AdminUser adminUser = adminUserManager.getById(adminUserId);
        List<Permission> permissions = permissionService.findByAdminUserId(adminUser.getId());
        adminUser.setPermissions(permissions);
        ResultData<AdminUser> result = new ResultData<>(adminUser);
        result.setResultMessage("登陆成功");

        securityHelper.sendRestResult(response, result);
    }
}
